package com.xudu.interceptors;

import cn.hutool.json.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.extension.api.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xudu.utils.Jwt;
import com.xudu.utils.Resoult;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * ClassName: JWTInterceptors
 * Description:
 *
 * @Author xudu
 * @Create 2024/4/10
 */

@Component
public class JWTInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        System.out.println("执行拦截器");
//        String authorization = request.getHeader("Authorization");
//        if (authorization!=null&&authorization.startsWith("Bearer ")){
//            String token = authorization.split(" ")[1];
//            boolean result = Jwt.verify(token);
//            if (result){
//                return true;
//            }
//        }


        String token = request.getHeader("token");
        boolean result = Jwt.verify(token);
        if (result){
            return true;
        }

        Resoult rp = Resoult.error("验证JWT失败！");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(rp);
        return false;



    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
